import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { accountLogin, logout } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import { setToken, setUser } from '@/utils/token';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    msg: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(accountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.status === 200) {
        reloadAuthorized();
        yield put(routerRedux.replace('/'));
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *logout({ payload }, { call, put }) {
      const response = yield call(logout);
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            data: {
              roles: 'guest',
              token: "",
              user: {},
            },
          },
        });
        reloadAuthorized();
        yield put(
          routerRedux.push({
            pathname: '/user/login',
          })
        );
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      if (payload.data) {
        setAuthority(payload.data.roles);
        setToken(payload.data.token);
        setUser(payload.data.id)
      }


      return {
        ...state,
        status: payload.status,
        msg: payload.msg
      };
    },
  },
};
